package com.github.bobjoy.java.classloader;

import com.github.bobjoy.java.classloader.loader.HotSwapURLClassLoader;

import java.lang.reflect.Method;

public class TestHotSwap {

    public static void main(String[] args) {
        // 开启线程，如果class文件有修改，就热替换
        new Thread(new MonitorHotSwap()).start();
    }

    static class MonitorHotSwap implements Runnable {
        // Hot就是用于修改，用来测试热加载
        private String className = "com.github.bobjoy.java.classloader.bean.Hot";
        private Class hotClazz = null;
        private HotSwapURLClassLoader hotSwapURLClassLoader = null;

        @Override
        public void run() {
            try {
                while (true) {
                    initLoad();
                    Object hot = hotClazz.newInstance();
                    Method method = hotClazz.getMethod("hot");
                    // 打印出相关信息
                    method.invoke(hot);
                    // 每隔10秒重新加载一次
                    Thread.sleep(10000);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        /**
         * 加载class
         */
        void initLoad() throws ClassNotFoundException {
            hotSwapURLClassLoader = HotSwapURLClassLoader.getClassLoader();
            // 如果Hot类被修改了，那么会重新加载，hotClass也会返回新的
            hotClazz = hotSwapURLClassLoader.load(className);
        }
    }
}

